package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-03
 * Time: 21:42
 */


//线程不安全例子
class Counter {
    private int count = 0;

    public void add() {
        synchronized (this) {//加锁，保证线程安全
            count++;
        }
        //count++;
        //三步操作
        //1. load,把内存中的数据读取到cpu寄存器中
        //2. add,把寄存器中的值，进行+1运算
        //3. save,把寄存器中的值写回到内存中
    }

    public int get() {
        return count;
    }
}

public class ThreadDemo13 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        //两个线程，分别对count++
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        t1.start();
        t2.start();


        t1.join();
        t2.join();

        //与预期结果100000不同（线程不安全问题，抢占式执行）
        System.out.println(counter.get());
    }
}
